package ch.ethz.fcl.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
import android.util.Log;
public class UDPServer implements Runnable {
		private static final String LOG_TAG = "UDP SERVER";
	
        public static final String SERVERIP = getLocalIpAddress();
        public static final int SERVERPORT = 51300;
        
        @Override
        public void run() {
            try {
                /* Retrieve the ServerName */
                InetAddress serverAddr = InetAddress.getByName(SERVERIP);
                Log.d(LOG_TAG, "S: Connecting...");
                /* Create new UDP-Socket */
                DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
                /* By magic we know, how much data will be waiting for us */
                byte[] buf = new byte[17];
                /* Prepare a UDP-Packet that can 
                 * contain the data we want to receive */
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                Log.d(LOG_TAG, "S: Receiving...");
                /* Receive the UDP-Packet */
                socket.receive(packet);
                Log.d(LOG_TAG, "S: Receiving...");
                Log.d(LOG_TAG, "S: Received: '" + new String(packet.getData()) + "'");
                Log.d(LOG_TAG, "S: Done.");
            } catch (Exception e) {
                Log.e(LOG_TAG, "S: Error", e);
            }           
        }
        
        public static String getLocalIpAddress() {
            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                    NetworkInterface intf = en.nextElement();
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e(LOG_TAG, ex.toString());
            }
            return null;
        }
}
